__author__ = 'root'
# -*- coding: utf-8 -*-

import MySQLdb as db
import mysql_log_class as log
import types
con = None
sql = None
array = None
tableName=None
db_host = 'localhost'
name = 'root'
db_pass = 'root'


def connectDB():
    db_name = 'demo_python'
    con = db.connect(db_host, name, db_pass, db_name)
    return con
    con.close()

#select fun
#@param string sql
#@retrun object data
def curFun(sql):
    con = connectDB()
    cur = con.cursor()
    cur.execute(sql)
    data = cur.fetchone()
    return data

#insert fun
#@param string sql
def insertFun(tableName,array):
    con = connectDB()
    cur = con.cursor()
    values = []
    column = ','.join(array)
    for key, val in array.items():
        if type(val)==type('a'):
            val = "'"+val+"'"
        values.append(val)
    value = ','.join(values)
    sql = 'insert into '+tableName+'( '+column+' ) values ( '+value+' )'
    try:
         cur.execute(sql)
         con.commit()
    except:
        con.rollback()
        log.errorLog('error','数据插入失败')


#create table
#@param string sql
def createTableFun(sql):
    con = connectDB()
    cur = con.cursor()
    cur.execute(sql)

def insertTestFun():
    con = connectDB()
    cur = con.cursor()
    #cur.execute('create table test(id int,info varchar(20))')
    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)
    con.commit()
    #sql = "insert into new_table( seg,name,address ) values ( '2','wangwan','shanxi' )"
    #value = ['wangwan', 2 ,'shanxi']
    #cursor.execute('insert into test values(%s,%s)',value)
    #cur.execute('insert into new_table values (%s,%s,%s)',value)
    #status = cur.fetchone()
